package com.fjh.config;

import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import feign.RequestInterceptor;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * mybatis的分页插件
 */
@Configuration
public class FeignInterceptor implements RequestInterceptor{
    /**
     * feign的拦截方法
     * 3种场景需要使用这个feign的拦截器传递token
     * 1.前端------>A------->B   (正常的用户token)
     * 2.Mq-------->B   (是我们应用的token)
     * 3.支付宝回调----->(放行)A------>B (是我们应用的token)
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {
        // 前端传进来的token在请求里面放着
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (!ObjectUtils.isEmpty(requestAttributes)) {
            // 1或者3场景
            HttpServletRequest request = requestAttributes.getRequest();
            String authorization = request.getHeader("Authorization");
            if (!StringUtils.isEmpty(authorization)) {
                // 1.种场景
                // 直接传递
                template.header("Authorization", authorization);
                return;
            }
        }
        // 说明是2和3场景 给一个应用的token
        template.header("Authorization", "bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJ3cml0ZSJdLCJleHAiOjM3NzUxMTA3OTksImp0aSI6IjYzNTFjZGMyLTYxNmUtNDJmMC1hMWY0LWE5Y2Q0MTQ1NWRkZiIsImNsaWVudF9pZCI6ImNsaWVudCJ9.WsGUY8OxA31rpwqeFK6m_XCYwyEH_VYRW9YGj--WTToPAEVvg5pHASdfc1rRBTdCNLKysOd-v9NRkk4sZ33l4hrT5vugqtfnlzDq_Ch1OPR7tS6H0CrgIHWfYBdsEknl9v0oMD13RNxz3jloenyUx3Cn0ngMkcBI_gwwQ6567pxuokjHyFxDZiaIaEklt4gwhej57R1Xyfyv7o6yLa9aJTBNrl96VNsHioaix7MQwP129FV0C7SPF-MKlWZetOtB4pwZWWI7t3hh1VUrdFdlhcY6nllPfM0Lh3V9KAWYVcXM4b3mh29nv2fFkYLQw7e8ykOCJL1ElpMUF5EiwfXNjQ");
    }
}
